/**
 * 获取host域名
 * @returns
 */
function hostUrl() {
    return location.protocol+'//'+location.host;
}

/**
 * 成功 失败消息
 */
function layerMessages(flag, error) {
    var fail = '<div class="layercont"><p class="layer-tit fail"><i class="iconfont">&#xe615;</i>操作失败！</p><p class="layer-info">'+
        error+'</p></div>';
    var success = '<div class="layercont"><p class="layer-tit fail"><i class="iconfont">&#xe614;</i>操作成功！</p></div>';
    layer.open({
        type: 1,
        title: false,
        time: 2000,
        closeBtn: 0,
        content: (flag === true) ? success : fail
    });
}

/**
 * 上传图片
 * @param file 需要上传的文件
 * @param callback 回调函数 接受参数url
 */
function upLoadImg(file, callback)
{
    var file = file;
    var form = new FormData();
    form.append('files', file);
    $.ajax({
        type: 'post',
        dataType: 'json',
        url: hostUrl() + '/files/upload_image',
        data: form,
        cache: false,
        contentType: false,
        processData: false,
        success: function(res) {
            console.log(res);
            if (res.status) {
                if (typeof callback === 'function') {
                    callback(res.data);
                }
            } else {
                alert(res.msg);
            }
        },
        error: function(e) {
            alert('网络错误');
        }
    });
}

$(document).ready(function(){
    /* 重置搜索条件 */
    $('button.button-reset').click(function(){
        var currentUrl = window.location.href;
        if (currentUrl.indexOf('?') != '-1') {
            var currentUrlPre = currentUrl.split('?')[0];
            window.location.href = currentUrlPre;
        } else {
            $(this).parents('form')[0].reset();
        }
    });

    //日期范围限制
    if ($('#in-date').size() > 0 && $('#out-date').size() > 0) {
        var start = {
            elem: '#in-date',
            format: 'YYYY-MM-DD',
            min: laydate.now(), //设定最小日期为当前日期
            max: laydate.now(+90),  //最大日期
            istime: true,
            isclear: false,
            istoday: false,
            issure: true,
            festival: true,
            choose: function(datas) {
                end.min = datas; //开始日选好后，重置结束日的最小日期
                var date = newDate(datas);
                //date.setDate(date.getDate()+20);
                //d = date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate();
                end.max = laydate.now(date.setDate(date.getDate()+20));
                end.start = datas; //将结束日的初始值设定为开始日
                $('#out-date').trigger('click');
            }
        };
        
        var end = {
            elem: '#out-date',
            format: 'YYYY-MM-DD',
            min: laydate.now(),
            //max: '2099-06-16',
            istime: true,
            isclear: false,
            istoday: false,
            issure: true,
            festival: true,
            choose: function(datas) {
                start.max = datas; //结束日选好后，重置开始日的最大日期
            }
        };
        $('#out-date').click(function(){
            laydate(end);
        });
        $('#in-date').click(function(){
            laydate(start);
        });
    }
    
    //lazyLoad
    if ($('img.lazy').size() > 0) {
        $('img.lazy').lazyload({
            skip_invisible : false
        }); //lazyLoad
    }
    
    if ($('.public-validate-form').size() > 0) {
        $('.public-validate-form').validate();
    }
    
    //CKedit 编辑器 js
    if ($('textarea.textarea-multipart-edit').size() > 0) {
        KindEditor.create('textarea.textarea-multipart-edit', {
            width : '85%',
            height : '250px'
        });
    }
    
    //wysiwyg 编辑器 js
    if ($('textarea.textarea-wysiwyg-edit').size() > 0) {
        $('.textarea-wysiwyg-edit').wysiwyg();
    }
    
    $('.checkbox').on('click', '.ckall', function(event){
        if ($(this).is(':checked') == false) {
            $('.checkbox-sub').prop('checked', false);
        } else {
            $('.checkbox-sub').prop('checked', 'true');
        }
        event.stopPropagation(); 
    });
    
    //插件-浮动
    if ($('.your-pinned').size()>0) {
        $('.your-pinned').pin({containerSelector:'.order-page', minWidth: 940});
    }
    
    //切换账号
    if ($('.so-switch').size() > 0) {
        $('.shop-option').on('click', '.so-switch dd', function(event){
            if (!$(this).hasClass('active')) {
                $this = $(this);//$(this).addClass('current').siblings().removeClass('current'); //当前点击弹框的加上Class记录
                $.ajax({
                    type: 'get',
                    dataType: 'jsonp',
                    jsonCallback: 'jsonCallback',
                    data : {uid : $this.data('user')},
                    url: $('#mySwitch .confirm').data('url')+'/login/userSwitchLogin.html',
                    success: function (json) {
                        if (json.status) {
                            //$('#mySwitch').modal('hide');
                            window.location.href = json.msg;
                        } else {
                            alert(json.msg);
                        }
                    }
                });
                //$('#mySwitch').modal();
            }
            event.stopPropagation();
        });
        /*$('#mySwitch').on('click', '.confirm', function(){
            $.ajax({
                type: 'get',
                dataType: 'jsonp',
                jsonCallback: 'jsonCallback',
                data : {uid : $('.so-switch dd.current').data('user')},
                url: $('#mySwitch .confirm').data('url')+'/login/userSwitchLogin.html',
                success: function (json) {
                    if (json.status) {
                        $('#mySwitch').modal('hide');
                        window.location.href = json.msg;
                    } else {
                        alert(json.msg);
                    }
                }
            });
            event.stopPropagation();
        });*/
        //异步切换账号
        var loading = false;
        var stop;
        $('.so-switch').hover(function () {
            stop = setTimeout(function () {
                loading = true;
                switchAjax();
            }, 500);
        }, function () {
            loading = false;
            clearTimeout(stop);
        });
        function switchAjax(){
            //ajax
            $.ajax({
                type: 'get',
                dataType: 'jsonp',
                jsonCallback: 'jsonCallback',
                url: $('#mySwitch .confirm').data('url')+'/login/userSwitch.html',
                success: function (json) {
                    if (json.status) {
                        $('.so-switch .show-popup').html(json.msg);
                    } else {
                        alert(json.msg);
                    }
                }
            });
        }
    }
    
    //公告
    if ($('.system-announcement').size()>0) {
        $.ajax({
            type: 'get',
            async: true,
            dataType: 'jsonp',
            jsonCallback: 'jsonCallback',
            url: hostUrl()+'/mailbox/announcement',
            success: function (data) {
                $('.system-announcement').html(data.announcement);
                if ($('#marquee').size() > 0) {
                    $('#marquee').marquee({yScroll: 'bottom'}); 
                }
            }
        });
    }
    
	/**
     * 写信
     */
    if ($('#message-write').size() > 0) {
        $('#message-write').submit(function(){
            var status = true;
            if (!$('input[name=sname]').hasClass('error')) {
                if ($('input[name=sname]').val().length == 0) {
                    $('input[name=sname]').addClass('error');
                    status = false;
                } else {
                    status = validateUserName($('input[name=sname]').val().trim());
                    if (!status) {
                        $('input[name=sname]').addClass('error');
                        $('input[name=sname]').after('<div class="error">请输入正确的用户名</div>');
                    }
                }
            } else {
                status = false;
            }

            if ($('input[name=title]').val().length == 0) {
                $('input[name=title]').addClass('error');
                status = false;
            }

            if ($('textarea[name=content]').val().length == 0) {
                $('textarea[name=content]').addClass('error');
                status = false;
            }
            return status;
        });

        $('input[name=sname]').change(function(){
            var nameUser = $('input[name=sname]').val().trim();
            if (nameUser.length > 0) {
                var status = validateUserName(nameUser);
                if (!status) {
                    if (!$(this).next().hasClass('error')) {
                        $(this).addClass('error');
                        $(this).after('<div class="error">请输入正确的用户名</div>');
                    }
                } else {
                    $(this).removeClass('error');
                    $(this).next('div.error').remove();
                }
            } else {
                $('input[name=sname]').addClass('error');
            }
        });

        /**
         * 输入数值
         */
        $('input[name=title],textarea[name=content]').keyup(function(){
            var val = $(this).val().trim();
            if(val.length > 0){
                $(this).removeClass('error');
            }else{
                $(this).addClass('error active');
            }
        });

        function validateUserName(userName){
            var status = false;
            $.ajax({
                type : 'POST',
                async : false,
                data :{'userName':userName},
                dataType : 'json',
                url : hostUrl() + '/mailbox/ajaxValidateName',
                success : function(data){
                    if(data.status){
                        status = true;
                    }
                }
            });
            return status;
        }
    }
    /**
     * 直接发送短信
     */
    $('#get-mobile-phone-captcha').click(function(){
        var obj = $(this);
        if (!$(this).hasClass('disabled')) {
            $.ajax({
                type : 'post',
                async: false,
                dataType : 'json',
                url : hostUrl() + '/validate/ajaxSendMessage',
                data : {},
                beforeSend : function(){},
                success : function(data) {
                    if ( data.status ) {
                        timing.setTime(obj);
                    } else {
                        alert(data.msg);
                    }
                }
            });
        }
    });

    /**
     * 获取手机号发送短信
     */
    if ($('#get-input-mobile-phone-captcha').size() > 0) {
        $('#get-input-mobile-phone-captcha').click(function(){
            var mobilePhone = $('input[name=mobilePhone]').val();
            var obj = $(this);
            if (mobilePhone.length == 11) {
                $.ajax({
                    type: 'post',
                    async: false,
                    dataType : 'json',
                    url: hostUrl() + '/validate/sendMessage',
                    data : {mobilePhone:mobilePhone},
                    beforeSend : function(){},
                    success : function(data) {
                        if (data.status) {
                            timing.setTime(obj);
                        } else {
                            obj.siblings('input').addClass('error').siblings('label.error').text(data.msg);
                        }
                    }
                });
            } else {
                obj.siblings('input').addClass('error').siblings('label.error').text('手机号码有误');
            }
        });
    }


    //验证码
    if ($('#ajaxJsonCaptcha').size() > 0) {
        $('#ajaxJsonCaptcha').click(function(){
            $.ajax({
                type: 'get',
                async: false,
                dataType : 'json',
                url: hostUrl() + '/validate/ajaxJsonCaptcha',
                success: function(json) {
                    $('#ajaxJsonCaptcha').html(json.image);
                }
            });
        });
    }

    /**
     * 发送短信，短信初始化化，从90秒
     * @type {{countdown: number, setTime: Function}}
     */
    var timing = {
        countdown : 90,
        setTime : function(obj) {
            if (timing.countdown == 0) {
                obj.removeClass("disabled");
                obj.text("获取验证码");
                timing.countdown = 90;
            } else {
                obj.addClass("disabled");
                obj.text('重新发送(' + timing.countdown + ')');
                timing.countdown--;
                setTimeout(function() {
                    timing.setTime(obj);
                }, 1000);
            }
        }
    }

    //账户收支
    var customer = {
        state :0,
        accountCommon: function() {
            //日期
            $('.customer-date-shift').on('click', 'ul li', function() {
                if ( ! $(this).hasClass('active')) {
                    $('input[name=page]').val(1);
                    var month = parseInt($(this).attr('data-month'));
                    $(this).siblings().removeClass('active');
                    $(this).addClass('active');
                    var now = new Date();
                    tbody = now.getFullYear() + '-' + parseInt(now.getMonth()+1) + '-' + now.getDate();
                    $('input[name=endData]').val(tbody);
                    var year1 = parseInt(now.getFullYear());
                    var month2 = parseInt(now.getMonth()) +1;
                    if (month2 <= month) {
                        year1 = year1 -1;
                        month2 = (month2 == month) ? 12 : parseInt(month2 +12 -month);
                    } else {
                        month2 = parseInt(month2-month);
                    }
                    startData = year1 + '-' + month2 + '-' + now.getDate();


                    $('input[name=startData]').val(startData);

                    ajaxAccountList();
                }
            });

            $('.customer-shift').on('click', 'ul li', function() {
                if ( ! $(this).hasClass('active')) {
                    $('input[name=page]').val(1);
                    var tag = $(this).attr('data-send');
                    var value = $(this).attr('data-status');
                    $('input[name='+tag+']').val(value);
                    $(this).siblings().removeClass('active');
                    $(this).addClass('active');
                    ajaxAccountList();
                }
            });

            $("#account-list").on('click', '.pagination ul li', function(event) {
               var href = $(this).children('a').attr('href');
               if (href.indexOf('/') > -1) {
                    var currentPage = href.substring(parseInt(href.lastIndexOf('/')) + 1);
                    $('input[name=page]').val(currentPage);
                    ajaxAccountList('paging');
               }
               return false;
             });

            $('#account-record-form').submit(function() {
                var orderId = $.trim($('input[name=order_id]').val());
                if (orderId.length > 0) {
                    customer.state = 1;
                    $('.customer-date-shift ul li.active').removeClass('active');
                    $('.customer-shift').each(function(i) {
                        $(this).children('ul').children('li.active').removeClass('active');
                        $(this).children('ul').children('li:first').addClass('active');
                    });
                    ajaxAccountList();
                } else {
                    /**
                    / 搜索条件 state 1代表可以搜索 0代表不可搜索
                    / 1,订单号不为空永远可以搜索，不为空则不可搜索
                    / 2,当上次搜索的时候 订单id不为空  下次如果订单id为空  给你机会用户 重置数据
                    */
                    if (customer.state === 1) {
                        ajaxAccountList();
                    }
                    customer.state = 0;
                }
                return false;
            });

            //开始时间
            $('input[name=startData]').click(function() {
                calendar.show({
                    id: this,
                    ok:selectDateAccount,
                    maxDay : $('input[name=endData]').val()
                });
            });

            //结束时间
            $('input[name=endData]').click(function() {
                calendar.show({
                    id: this, 
                    ok:selectDateAccount,
                    minDay : $('input[name=startData]').val()
                });
            });
        },
        init: function(){
            customer.accountCommon();
        }
    }
    customer.init();

    var scanRecommend = {
        init : function() {
                $(".super-table").on('click','.v-all',function(event){
                if(this.checked){
                    $(".hi-box :checkbox").prop("checked", true);
                }else{
                    $(".hi-box :checkbox").prop("checked", false);
                }
                event.stopPropagation();
            });

            function selectedId() {
                var ids = [];
                $('input[name=product_id]:checked').each(function(i){
                    ids.push($(this).val());
                });
                return ids;
            }

            $('.selected-product-save').on('click', function(){
                var id = selectedId();
                var type = $(this).data('type');
                $.ajax({
                    type: 'post',
                    async: false,
                    dataType : 'json',
                    url: hostUrl() + '/sacnrecommend/storeProduct',
                    data : {id:id,type:type},
                    beforeSend : function(){},
                    success : function(data) {
                        if (data.status) {
                            window.location.href = data.msg;
                        } else {
                            alert(data.msg);
                        }
                    }
                });
            });
        }
    }
    scanRecommend.init();
});

//账户收支
function ajaxAccountList() {
    if ('paging' ===arguments[0]) {
        $(window).scrollTop($('#firstAnchor').offset().top);
    }
    var mark = $('#account-record-form').attr('data-mark')+'/';

    $.ajax({
        type:'get',
        async:true,
        dataType:'json',
        data:$('form').serialize(),
        url:hostUrl()+ '/customer/' + mark + $('input[name=page]').val(),
        beforeSend:function(){
            $('#account-list').html('<div class="load-logo"><img src="/ucenter/images/tert.gif"></div>');
        },
        success:function(json){
            if (json.status) {
                $('#account-list').html(json.html);
            } else {
                alert('未知错误');
            }
        }
    });
}

//账户收支 选择筛选日期
function selectDateAccount() {
    $('.customer-date-shift ul li.active').removeClass('active');
    ajaxAccountList();
}

